<template>
  <div class="top-nav-wrap">
    <span
      v-for="ro in getNavRouter"
      :key="ro.route"
    >
      <el-button
        v-if="formInfoStore.hasFormButtonAuth(ro.type)"
        :class="currentPath === ro.route ? 'active' : ''"
        bg
        class="first-btn"
        text
        @click="onActiveRouter(ro.route)"
      >
        <el-icon size="18">
          <component :is="ro.icon" />
        </el-icon>
        {{ ro.title }}
      </el-button>
    </span>

    <div class="fun-btn-wrap">
      <el-button
        text
        bg
        class="first-btn"
        @click="handleOpenImportItem"
      >
        <el-icon size="18">
          <TablerUpload />
        </el-icon>
        {{ $t("formgen.topNav.importSubject") }}
      </el-button>
      <el-button
        text
        bg
        v-hasPermi="['form:template:save']"
        @click="saveProjectAsTemplateHandle"
      >
        <el-icon size="18">
          <TablerFilePlus />
        </el-icon>
        {{ $t("formgen.topNav.saveTemplate") }}
      </el-button>
      <el-dropdown class="mt7">
        <el-button
          text
          bg
        >
          <el-icon size="18">
            <TablerDots />
          </el-icon>
          {{ $t("formgen.topNav.other") }}
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="handleExportJson">{{ $t("formgen.topNav.exportJson") }}</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
  <template-create
    ref="templateCreateRef"
    :form-key="formKey"
  />
  <ImportFormItem
    ref="importItemsRef"
    :form-key="formKey"
    @success="handleImportItemSuccess"
  />
</template>

<script setup lang="ts">
import { computed, defineAsyncComponent, ref, watch } from "vue";
import { useFormInfo } from "@/stores/formInfo";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import { i18n } from "@/i18n";
import { batchSaveProjectItem } from "@/views/formgen/api/index";
import { formItemConvertData } from "@/views/formgen/utils/convert";
import { MessageUtil } from "@/utils/messageUtil";
import mittBus from "@/utils/mitt";
import { exportTemplateJson } from "@/api/project/template";
import { download } from "@/utils/tduck";
import TablerArrowsSplit2 from "~icons/tabler/arrows-split-2";
import TablerShirt from "~icons/tabler/shirt";
import TablerEdit from "~icons/tabler/edit";
import TablerChartRadar from "~icons/tabler/chart-radar";
import TablerTournament from "~icons/tabler/tournament";
import TablerUpload from "~icons/tabler/upload";
import TablerFilePlus from "~icons/tabler/file-plus";
import TablerDots from "~icons/tabler/dots";
import TablerUsersGroup from "~icons/tabler/users-group";
const TemplateCreate = defineAsyncComponent(() => import("@/views/project/template/create.vue"));
const ImportFormItem = defineAsyncComponent(() => import("./import/TextImportFormItem.vue"));

const navRouters = [
  {
    title: i18n.global.t("formgen.topNav.content"),
    icon: TablerEdit,
    route: "/project/form/editor/index",
    type: "editor"
  },
  {
    title: i18n.global.t("formgen.topNav.logic"),
    icon: TablerArrowsSplit2,
    route: "/project/form/editor/logic",
    type: "logic"
  },
  {
    title: i18n.global.t("formgen.topNav.theme"),
    icon: TablerShirt,
    route: "/project/form/editor/theme",
    type: "theme"
  }
];

const workflowRouter = {
  title: i18n.global.t("formgen.topNav.workFlow"),
  icon: TablerTournament,
  route: "/project/form/editor/workflow",
  type: "workflow"
};

const dimensionRouter = {
  title: i18n.global.t("formgen.topNav.dimension"),
  icon: TablerChartRadar,
  route: "/project/form/editor/dimension",
  type: "dimension"
};

const evaluationRouter = {
  title: i18n.global.t("formgen.topNav.evaluation"),
  icon: TablerUsersGroup,
  route: "/project/form/editor/evaluation",
  type: "evaluation"
};

const props = defineProps({
  formKey: {
    type: String,
    required: true
  }
});

defineEmits(["refresh"]);

const templateCreateRef = ref<any>(null);
const importItemsRef = ref<any>(null);

const saveProjectAsTemplateHandle = () => {
  templateCreateRef.value.handleOpen();
};
const handleOpenImportItem = () => {
  importItemsRef.value.showDialog();
};

const formInfoStore = useFormInfo();

const { formType } = storeToRefs(formInfoStore);

const getNavRouter = computed(() => {
  // 2.流程表单
  const result = [...navRouters];
  if (formType.value === 2) {
    result.push(workflowRouter);
  } else if (formType.value === 4) {
    result.push(dimensionRouter);
  } else if (formType.value === 6) {
    // result.push(dimensionRouter);
    result.push(evaluationRouter);
  }
  return result;
});

const currentPath = ref("");

const router = useRouter();

// 监听路由变化
watch(
  () => router.currentRoute.value.path,
  () => {
    currentPath.value = router.currentRoute.value.path;
  },
  {
    immediate: true
  }
);

const onActiveRouter = (path: string) => {
  router.replace({ path: path, query: { key: router.currentRoute.value.query.key } });
};

const handleImportItemSuccess = (fields: any[]) => {
  let itemList = fields.map(item => formItemConvertData(item, props.formKey));
  batchSaveProjectItem({
    formKey: props.formKey,
    list: itemList,
    operation: "add"
  }).then(() => {
    MessageUtil.success("保存成功");
    mittBus.emit("refreshFormList");
  });
};

const handleExportJson = () => {
  exportTemplateJson(props.formKey).then(response => {
    console.log(response);
    download(JSON.stringify(response.data), "template", ".json");
  });
};
</script>

<style scoped lang="scss">
.top-nav-wrap {
  height: 40px;
  line-height: 40px;
  border-bottom: var(--el-border);

  .first-btn {
    margin-left: 10px;
  }

  .first-btn.active {
    font-weight: bold;
  }

  .el-button {
    height: 30px !important;
    color: var(--el-text-color-primary);
  }

  .el-button.is-link {
    color: var(--el-text-color-primary);
  }

  .active {
    color: var(--el-color-primary);
  }

  .fun-btn-wrap {
    display: inline;
    float: right;
    margin-right: 2vw;
  }
}
</style>
